package com.kol.collect.service.admin.impl;

/**
 * Created by liukun on 20/3/6.
 */

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import com.kol.collect.common.AjaxJson;
import com.kol.collect.common.Constants;
import com.kol.collect.common.util.FastJsonUtils;
import com.kol.collect.common.util.TokenUtil;
import com.kol.collect.model.SysUser;
import com.kol.collect.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.TypeReference;
import com.kol.collect.dao.SysUserDao;
import com.kol.collect.model.PayloadInfo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class SysUserServiceImpl implements SysUserService {
    private Logger logger = LogManager.getLogger(SysUserServiceImpl.class);
    @Autowired
    private SysUserDao sysUserDao;
    @Resource
    private TokenUtil tokenUtil;
    @Autowired
    private JedisPool jedisPool;
    /**
     * web用户token过期时间
     */
    @Value("${user.token.expire}")
    private Integer userTokenExpire;

    @Override
    public AjaxJson<SysUser> jwtLogin(String data) {
        AjaxJson<SysUser> ajaxJson = new AjaxJson<>();
        ajaxJson.setStatus(AjaxJson.STATUS_AUTHENTICATION_FAIL);
        ajaxJson.setMsg(AjaxJson.MSG_AUTHENTICATION_FAIL);
        Map<String, String> dataMap = FastJsonUtils.toBean(data, new TypeReference<Map<String, String>>() {});
        String username = dataMap.get("username");
        String password = dataMap.get("password");
        SysUser user = new SysUser(username, password);
        SysUser sysUser = sysUserDao.findUser(user);

        if (username.equals(sysUser.getUsername()) && password.equals(sysUser.getPassword())) {
            String token = tokenUtil.getToken(new PayloadInfo(sysUser.getId(), sysUser.getUsername(), sysUser.getPhone()));
            if (token != null) {
                sysUser.setToken(token);
                sysUser.setPassword(null);
                ajaxJson.setStatus(AjaxJson.STATUS_SUCCESS);
                ajaxJson.setMsg(AjaxJson.MSG_SUCCESS);
                ajaxJson.setData(sysUser);
                return ajaxJson;
            }
        }
        return ajaxJson;
    }

    @Override
    public AjaxJson<SysUser> webLogin(String data) {
        Jedis jedis = jedisPool.getResource();
        logger.info("==========获取 jedis 连接=========");
        AjaxJson<SysUser> ajaxJson = new AjaxJson<>();
        ajaxJson.setStatus(AjaxJson.STATUS_AUTHENTICATION_FAIL);
        ajaxJson.setMsg(AjaxJson.MSG_AUTHENTICATION_FAIL);
        Map<String, String> dataMap = FastJsonUtils.toBean(data, new TypeReference<Map<String, String>>() {});
        String username = dataMap.get("username");
        String password = dataMap.get("password");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            ajaxJson.setStatus(AjaxJson.STATUS_PARAM_ERROR);
            ajaxJson.setMsg(AjaxJson.MSG_PARAM_ERROR);
            return ajaxJson;
        }
        SysUser user = new SysUser(username, password);
        SysUser sysUser = sysUserDao.findUser(user);
        if (null != sysUser && username.equals(sysUser.getUsername()) && password.equals(sysUser.getPassword())) {
            String token = genToken();
            sysUser.setToken(token);
            sysUser.setPassword(null);

            Map<String, String> userInfoMap = new HashMap<>();
            userInfoMap.put(Constants.USER_ID, sysUser.getId());
            userInfoMap.put(Constants.USER_NAME, sysUser.getUsername());
            userInfoMap.put(Constants.USER_PHONE, sysUser.getPhone() == null ? "" : sysUser.getPhone());
            userInfoMap.put(Constants.USER_TOKEN, token);
            try {
                if (!Constants.ORPERATION_OK.equals(jedis.hmset(Constants.WEB_USER_TOKEN + username, userInfoMap))) {
                    // 存入redis
                    ajaxJson.setStatus(AjaxJson.STATUS_REDIS_OP_FAIL);
                    ajaxJson.setMsg(AjaxJson.MSG_REDIS_OP_FAIL);
                    return ajaxJson;
                } else {
                    jedis.expire(Constants.WEB_USER_TOKEN + username, userTokenExpire);
                    ajaxJson.setStatus(AjaxJson.STATUS_SUCCESS);
                    ajaxJson.setMsg(AjaxJson.MSG_SUCCESS);
                    ajaxJson.setData(sysUser);
                    return ajaxJson;
                }

            } finally {
                jedis.close();
                logger.info("==========关闭 jedis 连接=========");
            }
        }
        return ajaxJson;
    }

    String genToken() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }

    @Override
    public AjaxJson<String> logout(String username) {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        ajaxJson.setStatus(AjaxJson.STATUS_EXCEPTION);
        ajaxJson.setMsg(AjaxJson.MSG_EXCEPTION);
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.del(Constants.WEB_USER_TOKEN + username);
            ajaxJson.setStatus(AjaxJson.STATUS_SUCCESS);
            ajaxJson.setMsg(AjaxJson.MSG_SUCCESS);
        } catch (Exception e) {
            ajaxJson.setStatus(AjaxJson.STATUS_REDIS_OP_FAIL);
            ajaxJson.setMsg(AjaxJson.MSG_REDIS_OP_FAIL);
            return ajaxJson;
        } finally {
            jedis.close();
        }
        return ajaxJson;
    }

}